from fastapi import APIRouter, Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional
import uuid
import base64
import random
import string

from app.core.database import get_db
from app.core.deps import get_current_user, get_tenant_id
from app.core.security import verify_password, create_access_token
from app.schemas.auth import LoginData, LoginResult, VerifyCodeResult, RegisterForm, TenantInfo, TenantVO, ChangePasswordRequest
from app.schemas.user import UserInfo
from app.models.user import User
from app.services.user import user_service
# from app.services.tenant import tenant_service
from app.utils.response import ResponseUtil
# from app.core.cache import cache_service

router = APIRouter()


@router.post("/login", summary="用户登录", response_model=LoginResult)
async def login(
    login_data: LoginData,
    db: AsyncSession = Depends(get_db)
):
    """用户登录接口 - 匹配plus-ui登录接口"""
    # 验证验证码（如果需要）
    if login_data.code and login_data.uuid:
        # TODO: 实现验证码验证逻辑
        # stored_code = await cache_service.get(f"captcha:{login_data.uuid}")
        # if not stored_code or stored_code.lower() != login_data.code.lower():
        #     raise HTTPException(
        #         status_code=status.HTTP_400_BAD_REQUEST,
        #         detail="验证码错误"
        #     )
        # await cache_service.delete(f"captcha:{login_data.uuid}")
        pass

    # 验证用户
    user = await user_service.get_by_username(db, username=login_data.username)
    if not user or not verify_password(login_data.password, user.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误"
        )

    # RuoYi字段：检查用户状态（0正常 1停用）
    if user.status != '0':
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户账户已被禁用"
        )

    # 验证租户ID（如果提供）
    if login_data.tenantId and user.tenant_id != login_data.tenantId:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="租户权限不匹配"
        )

    # 生成访问令牌 - 使用RuoYi字段
    access_token = create_access_token(
        subject=str(user.user_id),
        tenant_id=user.tenant_id
    )

    return LoginResult(access_token=access_token)


@router.post("/register", summary="用户注册")
async def register(
    register_data: RegisterForm,
    db: AsyncSession = Depends(get_db)
):
    """用户注册接口"""
    # 验证验证码
    if register_data.code and register_data.uuid:
        # TODO: 实现验证码验证逻辑
        # stored_code = await cache_service.get(f"captcha:{register_data.uuid}")
        # if not stored_code or stored_code.lower() != register_data.code.lower():
        #     raise HTTPException(
        #         status_code=status.HTTP_400_BAD_REQUEST,
        #         detail="验证码错误"
        #     )
        # await cache_service.delete(f"captcha:{register_data.uuid}")
        pass

    # 验证确认密码
    if register_data.confirmPassword and register_data.password != register_data.confirmPassword:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="密码和确认密码不一致"
        )

    # 检查用户名是否已存在
    existing_user = await user_service.get_by_username(db, username=register_data.username)
    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已存在"
        )

    # 创建新用户 - 使用RuoYi字段
    user_data = {
        "user_name": register_data.username,
        "nick_name": register_data.username,  # 默认昵称为用户名
        "password": register_data.password,
        "tenant_id": register_data.tenantId,
        "user_type": register_data.userType or "sys_user"
    }

    new_user = await user_service.create(db, obj_in=user_data)

    return ResponseUtil.success(
        data={"userId": new_user.user_id},
        message="注册成功"
    )


@router.post("/logout", summary="用户登出")
async def logout():
    """用户登出接口"""
    # TODO: 实现登出逻辑，如黑名单token等
    return ResponseUtil.success(message="登出成功")


@router.get("/code", summary="获取验证码", response_model=VerifyCodeResult)
async def get_code_img():
    """获取验证码图片"""
    # 生成随机验证码
    code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
    code_uuid = str(uuid.uuid4())

    # TODO: 将验证码存储到缓存中，有效期5分钟
    # await cache_service.set(f"captcha:{code_uuid}", code, expire=300)

    # 暂时使用简单的base64编码作为验证码图片占位符
    simple_svg = f'''<svg width="120" height="40" xmlns="http://www.w3.org/2000/svg">
        <rect width="120" height="40" fill="white" stroke="gray"/>
        <text x="60" y="25" text-anchor="middle" font-family="Arial" font-size="16" fill="black">{code}</text>
    </svg>'''

    img_str = base64.b64encode(simple_svg.encode()).decode()
    img_data = f"data:image/svg+xml;base64,{img_str}"

    return VerifyCodeResult(
        captchaEnabled=True,
        uuid=code_uuid,
        img=img_data
    )


@router.get("/tenant/list", summary="获取租户列表", response_model=TenantInfo)
async def get_tenant_list(
    isToken: bool = False,
    db: AsyncSession = Depends(get_db)
):
    """获取租户列表"""
    # TODO: 实现租户服务
    # tenants = await tenant_service.get_active_tenants(db)

    # 暂时返回默认租户
    tenant_list = [
        TenantVO(
            tenantId="1",
            companyName="默认租户",
            domain="default"
        )
    ]

    return TenantInfo(
        tenantEnabled=True,
        voList=tenant_list
    )


@router.post("/social/callback", summary="第三方登录回调")
async def social_callback(
    callback_data: LoginData,
    db: AsyncSession = Depends(get_db)
):
    """第三方登录回调处理"""
    # TODO: 实现第三方登录逻辑
    raise HTTPException(
        status_code=status.HTTP_501_NOT_IMPLEMENTED,
        detail="第三方登录功能暂未实现"
    )


@router.get("/me", summary="获取当前用户信息")
async def get_current_user_info(
    current_user: User = Depends(get_current_user)
):
    """获取当前登录用户信息 - RuoYi字段格式"""
    user_info = {
        "userId": current_user.user_id,
        "userName": current_user.user_name,
        "nickName": current_user.nick_name,
        "email": current_user.email,
        "phonenumber": current_user.phonenumber,
        "avatar": current_user.avatar,
        "sex": current_user.sex,
        "status": current_user.status,
        "admin": False,  # 需要根据角色判断
        "tenantId": current_user.tenant_id,
        "deptId": current_user.dept_id,
        "createTime": current_user.create_time.isoformat() if current_user.create_time else None,
        "updateTime": current_user.update_time.isoformat() if current_user.update_time else None,
        "roles": [],
        "permissions": []
    }

    return ResponseUtil.success(data=user_info)


@router.get("/permissions", summary="获取当前用户权限")
async def get_current_user_permissions(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """获取当前用户权限列表"""
    permissions = await user_service.get_user_permissions(
        db=db,
        user_id=current_user.user_id,
        tenant_id=tenant_id
    )
    return ResponseUtil.success(data=permissions)


@router.get("/menus", summary="获取当前用户菜单权限")
async def get_current_user_menus(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """获取当前用户的菜单权限树"""
    try:
        menu_permissions = await user_service.get_user_menu_permissions(
            db=db,
            user_id=current_user.user_id,
            tenant_id=tenant_id
        )

        # 构建菜单树结构
        from app.services.permission import permission_service
        menu_tree = permission_service._build_permission_tree(menu_permissions)

        return ResponseUtil.success(data=menu_tree)
    except Exception as e:
        # 如果出现错误，返回默认菜单结构
        default_menu_tree = [
            {
                "id": 1,
                "name": "仪表盘",
                "code": "dashboard",
                "type": "M",
                "path": "/dashboard",
                "component": "dashboard/index.vue",
                "icon": "Dashboard",
                "sort": 1,
                "children": []
            },
            {
                "id": 2,
                "name": "系统管理",
                "code": "system",
                "type": "M",
                "path": "/system",
                "component": None,
                "icon": "Setting",
                "sort": 2,
                "children": [
                    {
                        "id": 3,
                        "name": "用户管理",
                        "code": "system:user",
                        "type": "C",
                        "path": "/system/user",
                        "component": "system/user/index.vue",
                        "icon": "User",
                        "sort": 1,
                        "children": []
                    }
                ]
            }
        ]
        return ResponseUtil.success(data=default_menu_tree)


@router.put("/me", summary="更新当前用户信息")
async def update_current_user():
    """更新当前登录用户信息"""
    pass


@router.post("/change-password", summary="修改密码")
async def change_password(
    password_data: ChangePasswordRequest,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """修改用户密码"""
    # 验证原密码 - RuoYi字段名
    if not verify_password(password_data.oldPassword, current_user.password):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="原密码错误"
        )

    # 验证新密码和确认密码是否一致 - RuoYi字段名
    if password_data.newPassword != password_data.confirmPassword:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="新密码和确认密码不一致"
        )

    # 更新密码
    await user_service.update_password(db, user_id=current_user.user_id, password=password_data.newPassword)

    return ResponseUtil.success(message="密码修改成功")